package org.zjt.http.async;

import lombok.extern.slf4j.Slf4j;
import org.asynchttpclient.*;


import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Random;
import java.util.concurrent.ExecutionException;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-05-29 下午5:17
 * @see
 */

@Slf4j
public class Main extends StartBase {

    
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        DefaultAsyncHttpClientConfig clientConfig = new DefaultAsyncHttpClientConfig.Builder()
                .setConnectTimeout(1000).setMaxConnections(100).setReadTimeout(1000).setMaxRedirects(50)
                .setMaxConnectionsPerHost(80).setMaxRequestRetry(3).build();

        try(AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient(clientConfig)){

            long start = LocalDateTime.now().atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli();
            Random random = new Random();
            for (int i = 0; i < REQUEST_CNT; i++) {
                asyncHttpClient.executeRequest(asyncHttpClient.prepareGet(URLS.get(random.nextInt(URLS.size()))).build(),new MyAsyncHandler());
            }
            COUNT_DOWN_LATCH.await();
            long end = LocalDateTime.now().atZone(ZoneOffset.systemDefault()).toInstant().toEpochMilli();

            log.info("3.734 S 🎺消耗时间：{}",((end - start) / 1000.0));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




    @Slf4j
    static class MyAsyncHandler extends AsyncCompletionHandlerBase{

        @Override
        public void onThrowable(Throwable t) {
            log.info("onThrowable: {}" , COUNT.incrementAndGet());
            COUNT_DOWN_LATCH.countDown();
        }



        @Override
        public Response onCompleted(Response response) throws Exception {
            log.info("onBodyPartReceived: {} " , COUNT.incrementAndGet());
            COUNT_DOWN_LATCH.countDown();
            return response;
        }

    }
}

